import Vue from 'vue';
import Router from 'vue-router';
//引入子路由
import common from '@/router/common';
import sysOrgRouter from '@/router/sys/org/index';
import sysPermissionRouter from '@/router/sys/permission/index';
import sysConfigRouter from '@/router/sys/config/index';
import sysEnumsRouter from '@/router/sys/enums/index';
import sysJobRouter from '@/router/sys/job/index';
import sysLogRouter from '@/router/sys/log/index';
import sysCategoryRouter from '@/router/sys/category/index';
import codeGenerateRouter from '@/router/code/generate/index'
import codeExampleRouter from '@/router/code/example/index'
import codeTestRouter from '@/router/code/test/index'
import adminFormRouter from '@/router/admin/form/index'
import sysDataSourceRouter from '@/router/sys/datasource'
import sysRestRouter from '@/router/sys/rest'

import {fetch} from "../utils/http";


const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}


Vue.use(Router);

//免校验的url
const noAuthUrl = ['/sys','/403','/login','/404'];
const router = new Router({
    routes: [
        ...common,
        ...sysOrgRouter,
        ...sysPermissionRouter,
        ...sysConfigRouter,
        ...sysEnumsRouter,
        ...sysJobRouter,
        ...sysLogRouter,
        ...sysCategoryRouter,
        ...codeGenerateRouter,
        ...codeExampleRouter,
        ...codeTestRouter,
        ...adminFormRouter,
        ...sysDataSourceRouter,
        ...sysRestRouter
    ]
});

//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    if (!localStorage.token && to.path !== '/login') {
        next('/login');
    }else {
        // 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
        if (navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {
            Vue.prototype.$alert('vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看', '浏览器不兼容通知', {
                confirmButtonText: '确定'
            });
        } else {
            //权限验证
            if(noAuthUrl.includes(to.path)){
                next();
            }else {
                fetch('/api/sys/permission/sys_permission_url/checkPermission',{
                    permissionPath:to.path
                }).then((res)=>{
                    if(res.data){
                        next();
                    }else{
                        next("/403")
                    }
                })
            }
        }
    }
})

export default router
